/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import net.risesoft.risebi.collection.model.Level;
import net.risesoft.risebi.collection.service.LevelManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionInvocation;

/**
 * 级别管理action
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">丁兆俊</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/LevelAction")
public class LevelAction extends BaseAction implements Trimable {
	private static final long serialVersionUID = -1656386708797069195L;
	private static Log log = LogFactory.getLog(LevelAction.class);
	
	private LevelManager levelManager;
	private Level level;

	private String field; //Ext.ux.plugins.RemoteValidator
	private String value; //Ext.ux.plugins.RemoteValidator
	private String crud;
	private String ModalDialogFieldValue;

	@Action(value="prepareTreeGrid",
			results={@Result(name="success", location="/admin/level/levelTreeGrid.jsp")}
	)
	public String prepareTreeGrid() throws Exception {
		return SUCCESS;
	}

	@Action(value="prepareAdd",
			results={@Result(name="success", location="/admin/level/levelAdd.jsp")}
	)
	public String prepareAdd() throws Exception {
		return SUCCESS;
	}

	@Action(value="prepareEdit",
			results={@Result(name="success", location="/admin/level/levelEdit.jsp")}
	)
	public String prepareEdit() throws Exception {
		level = (Level)levelManager.getObject(Level.class, level.getGuid());
		return SUCCESS;
	}

	@Action(value="prepareSelectLevel",
			results={@Result(name="success", location="/admin/level/selectLevel.jsp")}
	)
	public String prepareSelectLevel() throws Exception {
		List<Level> lst1 = levelManager.getObjects(Level.class);
		this.json = JSONUtil.getJsonString("include","guid,parentGuid,name,code,path",lst1);

		this.source = "";
		level = (Level)levelManager.getObject(Level.class, this.ModalDialogFieldValue);
		if(level!=null){
			List lst2 = levelManager.getAncestor(level, "parentLevel");
			for(int i=0;i<lst2.size();i++){
				Level lvl = (Level)lst2.get(i);
				this.source += lvl.getGuid() + ";";
			}					
		}
		
		return SUCCESS;
	}

	@Action(value="list")
	public String list() throws Exception {
		try{
			List<Level> lst = null;
			if(this.active_node_id==null || this.active_node_id.trim().length()==0){
				lst = levelManager.getObjects(Level.class);
			}else{
				lst = levelManager.find("from Level m where m.parentLevel.guid='" + this.active_node_id + "'");
			}
			
			ArrayList al = new ArrayList();	
			for(Level t : lst){
				boolean isleaf = true;
				int count = levelManager.getCount("select count(*) from Level t where t.parentLevel.guid = '" + t.getGuid() + "'");
				if(count>0){
					isleaf = false;
				}
				LazyDynaBean ldb = new LazyDynaBean();
				ldb.set("guid", t.getGuid());
				ldb.set("parentGuid", t.getParentGuid());
				ldb.set("name", t.getName());
				ldb.set("code", t.getCode());
				//ldb.set("path", t.getPath());
				ldb.set("isleaf", isleaf);
				al.add(ldb);
			}	
			this.json = JSONUtil.getJsonString(null,null,al);
		}catch(Exception e){
			this.json = "[]";
		} 
		
		return AJAX;
	}	

	@Action(value="add")
	public String add() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String guid = new GUID().toString();
			level.setGuid(guid);
			
			String path = level.getCode().trim();
			Level tmp = (Level)levelManager.getObject(Level.class, level.getParentGuid());
			while(tmp!=null){
				path = tmp.getCode().trim() + "/" + path;
				tmp = (Level)levelManager.getObject(Level.class, tmp.getParentGuid());
			}
			//level.setPath(path);
			levelManager.saveObject(level);		
			
			ldb.set("success", true);
			ldb.set("reason", "增加成功！");
			
			ldb.set("guid", guid);
			ldb.set("parentGuid", level.getParentGuid());
			ldb.set("name", level.getName());
			ldb.set("code", level.getCode());
			//ldb.set("path", level.getPath());

			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="edit")
	public String edit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Level old_Level = (Level)levelManager.getObject(Level.class, level.getGuid());		
			String old_code = old_Level.getCode();
			String new_code = level.getCode();
			//String old_path = old_Level.getPath();
			//int j = old_path.lastIndexOf(old_code);
			
			old_Level.setCode(new_code);
			old_Level.setName(level.getName());
			//old_Level.setPath(old_path.substring(0, j) + new_code);
			levelManager.saveObject(old_Level);	
			
			if(!old_code.trim().equalsIgnoreCase(new_code.trim())){
				ArrayList lst = new ArrayList();
				levelManager.recursiveGetAll(level, "parentLevel", lst);
				for(int i=0;i<lst.size();i++){
		    		Level levelObj = (Level)lst.get(i);		    		
		    		String path = levelObj.getCode().trim();
					Level tmp = (Level)levelManager.getObject(Level.class, levelObj.getParentGuid());
					while(tmp!=null){
						path = tmp.getCode().trim() + "/" + path;
						tmp = (Level)levelManager.getObject(Level.class, tmp.getParentGuid());
					}
					//levelObj.setPath(path);
					levelManager.saveObject(levelObj);	
		    	}				
			}
				
			
			ldb.set("success", true);
			ldb.set("reason", "修改成功！");
			
			ldb.set("name", old_Level.getName());
			ldb.set("code", old_Level.getCode());
			//ldb.set("path", old_Level.getPath());

			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			levelManager.removeObject(Level.class, node); 		
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="validateField")
	public String validateField() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();		
		try{
			if("level.name".equals(this.field)){				
				if("c".equals(this.crud)){
					List lst = levelManager.find("from Level r where r.name = '" + this.value + "'");
					if(lst.size()>0){
						ldb.set("success", true);
						ldb.set("valid", false);
						ldb.set("reason", "名称重复。");
						this.json = JSONObject.fromObject(ldb).toString();
						
						return "validateField";
					}
				}else{
					List lst = levelManager.find("from Level r where r.name = '" + this.value + "' and r.guid != '" + node + "'");
					if(lst.size()>0){
						ldb.set("success", true);
						ldb.set("valid", false);
						ldb.set("reason", "名称重复。");
						this.json = JSONObject.fromObject(ldb).toString();
						
						return "validateField";						
					}
				}			
			}
			ldb.set("success", true);
			ldb.set("valid", true);
			ldb.set("reason", "validateField success");
			this.json = JSONObject.fromObject(ldb).toString();			
		}catch(Exception e){
			ldb.set("success", true);
			ldb.set("valid", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();			
		}
		
		return AJAX;		
	}

	@Action(value="export")
	public String export() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			List<Level> ms = levelManager.getObjects(Level.class);
			String jsonLevels = JSONUtil.getJsonString("include", "guid,parentGuid,name,code,path", ms);
			String filePath = this.getRealPath();
	        if(!filePath.endsWith(File.separator)){
	        	filePath = filePath + File.separator;
	        }
			filePath = filePath + "levels.json";
			
			FileOutputStream fos = new FileOutputStream(filePath);
	        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
	        osw.write(jsonLevels);
	        osw.close();
	        fos.close();
	        
			ldb.set("success", true);
			ldb.set("reason", "导出成功! 文件保存在：\r\n" + filePath);
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="importFromJson")
	public String importFromJson() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String filePath = this.getRealPath();
	        if(!filePath.endsWith(File.separator)){
	        	filePath = filePath + File.separator;
	        }
			filePath = filePath + "levels.json";
			File f = new File(filePath);
			if(f.exists()){
				//levelManager.execute("delete Level");
				List lst = levelManager.getObjects(Level.class);
				levelManager.removeObjects(lst);
				
				FileInputStream fis = new FileInputStream(f);
				String jsonLevels = IOUtils.toString(fis, "utf-8");
		        fis.close();
		        
		        Level[] ms = (Level[])JSONUtil.stringToArray(json, Level.class);
				for (Level m : ms){
					levelManager.saveObject(m);
				}		        
				
				ldb.set("success", true);
				ldb.set("reason", "导入成功!");				
			}else{
				ldb.set("success", false);
				ldb.set("reason", "没有找到这个文件：\r\n" + filePath);				
			}
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	/* (non-Javadoc)
	 * @see net.risesoft.commons.struts2extension.Trimable#afterTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void afterTrim(ActionInvocation invocation) {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see net.risesoft.commons.struts2extension.Trimable#preTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public boolean preTrim(ActionInvocation invocation) {
		return true;
	}

	public LevelManager getLevelManager() {
		return levelManager;
	}

	public void setLevelManager(LevelManager levelManager) {
		this.levelManager = levelManager;
	}

	public Level getLevel() {
		return level;
	}

	public void setLevel(Level level) {
		this.level = level;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getCrud() {
		return crud;
	}

	public void setCrud(String crud) {
		this.crud = crud;
	}

	public String getModalDialogFieldValue() {
		return ModalDialogFieldValue;
	}

	public void setModalDialogFieldValue(String modalDialogFieldValue) {
		ModalDialogFieldValue = modalDialogFieldValue;
	}
	
}
